package com.lishangshan.oas_system.controller;

import com.github.pagehelper.util.StringUtil;
import com.lishangshan.oas_system.model.dao.informdao.InformRelationDao;
import com.lishangshan.oas_system.model.dao.maildao.MailreciverDao;
import com.lishangshan.oas_system.model.dao.processdao.NotepaperDao;
import com.lishangshan.oas_system.model.dao.user.DeptDao;
import com.lishangshan.oas_system.model.dao.user.PositionDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.mail.Mailreciver;
import com.lishangshan.oas_system.model.entity.notice.NoticeUserRelation;
import com.lishangshan.oas_system.model.entity.process.Notepaper;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.utils.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 用戶 面板操作
 */
@Controller
@RequestMapping("/")
public class UserpanelController {
    @Autowired
    private UserDao udao;
    @Autowired
    private DeptDao ddao;
    @Autowired
    private PositionDao pdao;
    @Autowired
    private InformRelationDao irdao;
    @Autowired
    private MailreciverDao mdao;
    @Autowired
    private NotepaperDao ndao;


    // 再进入 信息面板 时 做了 一系列的查找
    @RequestMapping("userpanel")
    public String index(@SessionAttribute("userId") Long userId, Model model, HttpServletRequest req,
                        @RequestParam(value = "page", defaultValue = "0") int page,
                        @RequestParam(value = "size", defaultValue = "10") int size) {

        Pageable pa = new PageRequest(page, size);
        User user = null;
        if (!StringUtil.isEmpty((String) req.getAttribute("errormess"))) {
            user = (User) req.getAttribute("users");
            req.setAttribute("errormess", req.getAttribute("errormess"));
        } else if (!StringUtil.isEmpty((String) req.getAttribute("success"))) {
            user = (User) req.getAttribute("users");
            req.setAttribute("success", "fds");
        } else {
            //找到这个用户
            user = udao.findOne(userId);
        }

        //找到部门名称
        String deptname = ddao.findname(user.getDept().getDeptId());

        //找到职位名称
        String positionname = pdao.findById(user.getPosition().getId());

        //找未读通知消息
        List<NoticeUserRelation> noticelist = irdao.findByReadAndUserId(false, user);

        //找未读邮件
        List<Mailreciver> maillist = mdao.findByReadAndDelAndReciverId(false, false, user);

        //找便签
        Page<Notepaper> list = ndao.findByUserIdOrderByCreateTimeDesc(user, pa);

        List<Notepaper> notepaperlist = list.getContent();

        model.addAttribute("user", user);
        model.addAttribute("deptname", deptname);
        model.addAttribute("positionname", positionname);
        model.addAttribute("noticelist", noticelist.size());
        model.addAttribute("maillist", maillist.size());
        model.addAttribute("notepaperlist", notepaperlist);
        model.addAttribute("page", list);
        model.addAttribute("url", "panel");

        return "user/userpanel";
    }

    // panel 便签 分页操作
    @RequestMapping("/panel")
    public String panel(@SessionAttribute("userId") Long userId,
                        @RequestParam(value = "page", defaultValue = "1") Integer page,
                        HttpServletRequest req,
                        Model model) {
        User user = null;
        Pageable pa = new PageRequest(page, 10);
        if (!StringUtil.isEmpty((String) req.getAttribute("errormess"))) {
            user = (User) req.getAttribute("users");
            req.setAttribute("errormess", req.getAttribute("errormess"));
        } else if (!StringUtil.isEmpty((String) req.getAttribute("success"))) {
            user = (User) req.getAttribute("users");
            req.setAttribute("success", "fds");
        } else {
            //找到这个用户
            user = udao.findOne(userId);
        }
        //找便签
        Page<Notepaper> list = ndao.findByUserIdOrderByCreateTimeDesc(user, pa);
        // 数据 信息
        List<Notepaper> notepaperlist = list.getContent();
        // 分页数据
        model.addAttribute("user", user);
        model.addAttribute("page", list);
        model.addAttribute("notepaperlist", notepaperlist);
        model.addAttribute("url", "panel");
        return "user/panel";
    }

    //  writep 修改 添加 我的便签
    @RequestMapping("/writep")
    public String update(Notepaper notepaper, @SessionAttribute("userId") Long userId, Model model) {
        User user = udao.findOne(userId);
        notepaper.setUserId(user);
        notepaper.setCreateTime(new Date());
        Notepaper save = ndao.save(notepaper);
        System.out.println("修改 或 添加 便簽 成功");
        model.addAttribute("success", "12121");
        return "redirect:/userpanel";
    }

    // notepaper 刪除 便簽
    @RequestMapping("/notepaper")
    @ResponseBody
    public String notepaper(@RequestParam("id") Long id, Model model) {
        // 如果 删除成功 则 返回 1 否则返回 0
        int i = 0;
        try {
            ndao.delete(id);
            i = 1;
            model.addAttribute("success", "12121");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errormess", "删除失败");
        }
        return "" + i;
    }
    @Autowired
    private FileUpload fileUpload;

    // saveuser 修改 用户 信息
    @RequestMapping("saveuser")
    public String saveuser(User user, HttpServletRequest request, @SessionAttribute("userId") Long userId) throws IOException {
//        User o = (User) request.getSession().getAttribute("user");
        // 取 用户 未 修改的 值 来补充一些不许改变的值
        User one = udao.findOne(userId);
        System.out.println("查询值oneUser = " + one);

        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
        MultipartFile file = mreq.getFile("filePath");
        String imgPath = fileUpload.imgUpload(file, request);

        System.out.println("前台获取值user = " + user);

        /* user.setPassword(user.getPassword().length() == 0 ? o.getPassword() : user.getPassword());*/
        user.setSalary(one.getSalary());
        user.setHireTime(one.getHireTime());
        user.setFatherId(one.getFatherId());
        user.setSuperman(one.getSuperman());
        user.setDept(one.getDept());
        user.setPosition(one.getPosition());
        user.setRole(one.getRole());

        // 拼音
        user.setPinyin(one.getPinyin());
        // 设置 最后修改时间为当前时间
        user.setModifyTime(new Date());

        // id 和 图片 路径
        user.setUserId(userId);
        user.setImgPath(imgPath);
        System.out.println("修改完整值 user01 =" + user);
        try {
            User save = udao.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/userpanel";
    }

}
